package com.zfb.videoscript.core

import android.accessibilityservice.AccessibilityService
import android.view.accessibility.AccessibilityNodeInfo
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

data class NodePath(
    val id: String? = null,          // 资源ID
    val text: String? = null,        // 文本内容
    val className: String? = null,   // 类名
    val desc: String? = null,        // 描述
    val index: Int = -1,            // 索引位置
    val bounds: Pair<Int, Int>? = null  // 固定坐标
)

data class NodeConfig(
    val platform: String,           // 平台（支付宝/拼多多）
    val likeButton: NodePath,      // 点赞按钮
    val videoContainer: NodePath,   // 视频容器
    val redPacketButton: NodePath, // 红包按钮
    val commentButton: NodePath,   // 评论按钮
    val shareButton: NodePath      // 分享按钮
)

class NodeLocator(private val service: AccessibilityService) {
    private val _currentNode = MutableStateFlow<AccessibilityNodeInfo?>(null)
    val currentNode: StateFlow<AccessibilityNodeInfo?> = _currentNode

    // 预定义的平台配置
    private val platformConfigs = mapOf(
        "alipay" to NodeConfig(
            platform = "alipay",
            likeButton = NodePath(
                id = "com.alipay.mobile.nebula:id/like_button",
                className = "android.widget.ImageView",
                bounds = Pair(540, 960)
            ),
            videoContainer = NodePath(
                className = "android.widget.FrameLayout",
                index = 0
            ),
            redPacketButton = NodePath(
                text = "领取红包",
                className = "android.widget.Button"
            ),
            commentButton = NodePath(
                id = "com.alipay.mobile.nebula:id/comment_button",
                className = "android.widget.ImageView"
            ),
            shareButton = NodePath(
                id = "com.alipay.mobile.nebula:id/share_button",
                className = "android.widget.ImageView"
            )
        ),
        "pdd" to NodeConfig(
            platform = "pdd",
            likeButton = NodePath(
                id = "com.xunmeng.pinduoduo:id/like_btn",
                className = "android.widget.ImageView",
                bounds = Pair(540, 960)
            ),
            videoContainer = NodePath(
                className = "android.widget.FrameLayout",
                index = 0
            ),
            redPacketButton = NodePath(
                text = "领取红包",
                className = "android.widget.Button"
            ),
            commentButton = NodePath(
                id = "com.xunmeng.pinduoduo:id/comment_btn",
                className = "android.widget.ImageView"
            ),
            shareButton = NodePath(
                id = "com.xunmeng.pinduoduo:id/share_btn",
                className = "android.widget.ImageView"
            )
        )
    )

    fun findNode(path: NodePath): AccessibilityNodeInfo? {
        val rootNode = service.rootInActiveWindow ?: return null
        return findNodeRecursive(rootNode, path)
    }

    private fun findNodeRecursive(node: AccessibilityNodeInfo, path: NodePath): AccessibilityNodeInfo? {
        // 检查当前节点是否匹配
        if (isNodeMatch(node, path)) {
            return node
        }

        // 递归检查子节点
        for (i in 0 until node.childCount) {
            val child = node.getChild(i) ?: continue
            val result = findNodeRecursive(child, path)
            if (result != null) {
                return result
            }
        }

        return null
    }

    private fun isNodeMatch(node: AccessibilityNodeInfo, path: NodePath): Boolean {
        // ID匹配
        if (path.id != null && node.viewIdResourceName != path.id) {
            return false
        }

        // 文本匹配
        if (path.text != null && node.text?.toString() != path.text) {
            return false
        }

        // 类名匹配
        if (path.className != null && node.className?.toString() != path.className) {
            return false
        }

        // 描述匹配
        if (path.desc != null && node.contentDescription?.toString() != path.desc) {
            return false
        }

        // 索引匹配
        if (path.index != -1 && node.parent?.let { parent ->
            (0 until parent.childCount).firstOrNull { parent.getChild(it) == node } != path.index
        } == true) {
            return false
        }

        return true
    }

    fun getConfig(platform: String): NodeConfig? {
        return platformConfigs[platform]
    }

    fun updateCurrentNode() {
        _currentNode.value = service.rootInActiveWindow
    }

    fun clearCurrentNode() {
        _currentNode.value = null
    }
} 